package com.aerospace.rpc3;

import com.aerospace.IUserService;
import com.aerospace.User;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @Author: Aerospace
 * @Date: 2021/5/12 20:35
 * @Description: Dream begins
 *
 * 使用动态代理生成service类供客户端调用 彻底隐藏掉所有细节
 */
public class Stub {
    public static IUserService getSub(){
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket("127.0.0.1",8099);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                dos.writeInt(123);
                //发送出要查询的id
                socket.getOutputStream().write(baos.toByteArray());
                socket.getOutputStream().flush();
                //接收服务端返回的结果
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                int id = dis.readInt();
                String name = dis.readUTF();
                Object user = new User(id,name);
                return user;
            }
        };

        //类加载器，实现的接口，处理器当前的handler
        Object o = Proxy.newProxyInstance(IUserService.class.getClassLoader(),new Class[]{IUserService.class},handler);
        System.out.println(o.getClass().getName());
        System.out.println(o.getClass().getInterfaces());
        return (IUserService) o;
    }
}
